<template>
  <el-dialog :visible="childVisible"
             title="添加子单"
             :before-close="close"
             width="75%"
             top="12vh"
             :close-on-click-modal="false"
             append-to-body>
    <el-form ref="form"
             :model="form"
             label-width="100px">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="合同编号">
            <dn-input-multiple v-model="form.contractNos"
                               placeholder="请输入合同编号" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="发货时间">
            <el-date-picker v-model="form.deliveryTime"
                            type="daterange"
                            range-separator="至"
                            start-placeholder="开始日期"
                            end-placeholder="结束日期"
                            @change="changeTime(0)" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="要求到货时间">
            <el-date-picker v-model="form.receivingTime"
                            type="daterange"
                            range-separator="至"
                            start-placeholder="开始日期"
                            end-placeholder="结束日期"
                            @change="changeTime(1)" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="发货省市区">
            <area-cascader v-model="form.fromAddress"
                           :props="props" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="12">
        <el-col :span="6">
          <el-form-item label="收货省市区">
            <area-cascader v-model="form.toAddress"
                           :props="props" />
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="收货方名称">
            <el-input v-model="form.consigneeName"
                      placeholder="请输入收货方名称"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="发货方名称">
            <el-input v-model="form.customerName"
                      placeholder="请输入发货方名称"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="运输方式">
            <Select v-model="form.shipMode"
                    :options="shipModeOptions"
                    :placeholder="'请选择运输方式'" />
          </el-form-item>
        </el-col>
        <el-col :span="3">
          <el-button type="primary"
                     @click="page = 1; handleQuery()">查询</el-button>
          <el-button type="primary"
                     @click="clean">清空</el-button>
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer"
         class="dialog-footer">
      <el-pagination :current-page="page"
                     :page-size="pageSize"
                     :total="total"
                     :page-sizes="[10, 20, 50, 100]"
                     layout="total, sizes, prev, pager, next, jumper"
                     @size-change="handleSizeChange"
                     @current-change="handleCurrentChange">
      </el-pagination>
      <el-button type="default"
                 @click="close">取消</el-button>
      <el-button type="primary"
                 @click="container">确定</el-button>
    </div>
    <div class="tableCon">
      <order-list ref="orderlist"
                  :current-data="currentData"
                  :table-data="tableData"
                  :amount="amount"
                  :col-width="183"
                  :table-footer="false"
                  :selection-flag="true"
                  :operation-flag="false" />
    </div>
  </el-dialog>
</template>

<script>
import AreaCascader from "@basic/area/AreaCascader.vue";
import OrderList from "./OrderList.vue";
import { transport } from "@/api/index";
import Select from "@/components/advance/Select";
import { shipModeOptions } from "@/libs/constant.js"

export default {
  name: "AddChildOrderDialog",
  components: { AreaCascader, OrderList, Select },
  props: {
    childVisible: Boolean,
    tableData: {
      type: Array,
      default: () => []
    },
    shipMode: Number
  },
  data () {
    return {
      props: {
        label: 'name',
        value: 'areaCode',
        checkStrictly: true
      },
      form: {
        contractNos: [],
        deliveryTime: null,
        fromTimeBegin: null,
        fromTimeEnd: null,
        receivingTime: null,
        toTimeBegin: null,
        toTimeEnd: null,
        fromAddress: {
          city: null,
          cityCode: null,
          district: null,
          districtCode: null,
          province: null,
          provinceCode: null
        },
        toAddress: {
          city: null,
          cityCode: null,
          district: null,
          districtCode: null,
          province: null,
          provinceCode: null
        },
        consigneeName: null,
        customerName: null,
        shipMode: this.shipMode
      },
      shipModeOptions,
      currentData: [],
      amount: {
        totalQuantity: 0,
        calculateWeight: 0,
        calculateVolume: 0
      },
      page: 1,
      pageSize: 10,
      total: 0
    };
  },
  created () {
    this.getList({
      page: this.page,
      size: this.pageSize,
      sort: [
        {
          asc: false,
          name: "createAt"
        }
      ],
      status: [10],
      combine: 0,
      shipMode: this.shipMode,
      waybillTypes: [20]
    });
  },
  methods: {
    async getList (params) {
      const { code, data } = await transport.search({ ...params });
      if (code !== 0) return;
      this.total = data.total;
      this.currentData = data.records;
      this.currentData &&
        this.currentData.map((item) => {
          this.amount.totalQuantity = item.totalQuantity;
          this.amount.calculateWeight = item.calculateWeight;
          this.amount.calculateVolume = item.calculateVolume;
        });
    },
    // 时间
    changeTime (type) {
      if (type) {
        this.form.toTimeBegin = this.form.receivingTime ? this.$moment(this.form.receivingTime[0]).format("YYYY-MM-DD HH:mm:ss") : null;
        this.form.toTimeEnd = this.form.receivingTime ? this.$moment(this.form.receivingTime[1]).format("YYYY-MM-DD HH:mm:ss") : null;
      } else {
        this.form.fromTimeBegin = this.form.deliveryTime ? this.$moment(this.form.deliveryTime[0]).format("YYYY-MM-DD HH:mm:ss") : null;
        this.form.fromTimeEnd = this.form.deliveryTime ? this.$moment(this.form.deliveryTime[1]).format("YYYY-MM-DD HH:mm:ss") : null;
      }
    },
    // 查询
    handleQuery () {
      let params = {
        page: this.page,
        size: this.pageSize,
        sort: [
          {
            asc: false,
            name: "createAt"
          }
        ],
        status: [10],
        waybillTypes: [20],
        shipMode: this.form.shipMode,
        combine: 0
      };
      for (let key in this.form) {
        if (this.form[key] && key != "fromAddress" && key != "toAddress")
          params[key] = this.form[key];
        if (key === "fromAddress" && this.form?.fromAddress?.provinceCode) {
          // k首字母转大写 + 从k索引1的位置提取字符，如 address => Address
          for (let k in this.form.fromAddress) {
            let toUpper = k[0].toUpperCase() + k.substr(1);
            let newKey = `from${toUpper}`;
            params[newKey] = this.form[key][k];
          }
        }
        if (key === "toAddress" && this.form?.toAddress?.provinceCode) {
          for (let k in this.form.toAddress) {
            let toUpper = k[0].toUpperCase() + k.substr(1);
            let newKey = `to${toUpper}`;
            params[newKey] = this.form[key][k];
          }
        }
      }
      this.getList(params);
    },
    // 分页数量改变
    handleSizeChange (value) {
      this.pageSize = value;
      this.handleQuery();
    },
    // 当前页数改变
    handleCurrentChange (value) {
      this.page = value;
      this.handleQuery();
    },
    anyInput (arr) {
      this.form.contractNos = arr.length ? arr : null;
    },
    // 取消
    close () {
      this.$emit("update:childVisible", false);
    },
    // 清空
    clean () {
      this.form = {
        contractNos: [],
        deliveryTime: null,
        fromTimeBegin: null,
        fromTimeEnd: null,
        receivingTime: null,
        toTimeBegin: null,
        toTimeEnd: null,
        fromAddress: {
          city: "",
          cityCode: "",
          district: "",
          districtCode: "",
          province: "",
          provinceCode: ""
        },
        toAddress: {
          city: "",
          cityCode: "",
          district: "",
          districtCode: "",
          province: "",
          provinceCode: ""
        },
        consigneeName: null,
        customerName: null,
        shipMode: null
      };
      this.getList({
        page: this.page,
        size: this.pageSize,
        sort: [
          {
            asc: false,
            name: "createAt"
          }
        ],
        status: [10],
        combine: 0,
        waybillTypes: [20],
        shipMode: null
      });
    },
    // 确定
    container () {
      if (
        this.$refs.orderlist.selectData &&
        this.$refs.orderlist.selectData.length > 0
      ) {
        let ids = this.tableData.map((item) => {
          return item.id;
        });
        let data = [];
        let invalidWaybill = [];
        this.$refs.orderlist.selectData.map((ele) => {
          // 当前选择的运单不属于合单子单且未过关账期
          if (!ids.includes(ele.id)) {
            data.push({
              ...ele,
              transportRequirement: { ...ele },
              calculateWeight: Number(ele.calculateWeight.toFixed(2)),
              calculateVolume: Number(ele.calculateVolume.toFixed(2)),
              totalQuantity: ele.totalQuantity,
              calculateValue: ele.calculateValue
            });
          }
          if (ele.billDayStatus) {
            invalidWaybill.push(ele.contractNo)
          }
        });
        if (this.tableData.length + data.length > 100) {
          return this.$message.error("合单子单数不能大于100单");
        }
        if (invalidWaybill.length) {
          this.$confirm(
            `运单(合同号${invalidWaybill.toString()})已过关账期，加入合单将影响合单报价，是否确定继续操作?`,
            "提示",
            {
              confirmButtonText: "确定",
              type: "warning",
              closeOnClickModal: false
            }
          ).then(() => {
            this.$emit("changeTableData", data);
            this.close();
          });
        } else {
          this.$emit("changeTableData", data);
          this.close();
        }
      } else {
        this.$message.error("请勾选运单");
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.tableCon {
  height: 510px;
  overflow-x: hidden;
}
/deep/ .el-dialog__body {
  padding: 20px 20px 0 20px;
  color: var(--prev-color-text-regular);
  font-size: 14px;
  word-break: break-all;
}
</style>
